package com.youlai.boot.modules.area.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.boot.modules.area.mapper.AreaMapper;
import com.youlai.boot.modules.area.model.Area;
import com.youlai.boot.modules.area.model.AreaForm;
import com.youlai.boot.modules.area.model.AreaPageQuery;
import com.youlai.boot.modules.area.model.AreaVO;
import com.youlai.boot.modules.area.service.AreaService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youlai.boot.modules.area.model.AreaConverter;
import com.youlai.boot.modules.category.service.CategoryService;
import com.youlai.boot.modules.category.model.Category;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class AreaServiceImpl extends ServiceImpl<AreaMapper, Area> implements AreaService {

    private final AreaConverter areaConverter;
    private final CategoryService categoryService;

    @Override
    public Page<AreaVO> getAreaPage(AreaPageQuery queryParams) {
        Page<AreaVO> page = new Page<>(queryParams.getPageNum(), queryParams.getPageSize());
        return baseMapper.getAreaPage(page, queryParams);
    }

    @Override
    public AreaForm getAreaForm(Long areaId) {
        Area entity = this.getById(areaId);
        AreaForm form = areaConverter.toForm(entity);

        if (entity.getCategoryId() != null) {
            Category category = categoryService.getById(entity.getCategoryId());
            form.setCategoryName(category.getName());
        }
        return form;
    }

    @Override
    public Long saveArea(AreaForm form) {
        Area entity = areaConverter.toEntity(form);
        this.save(entity);
        return entity.getId();
    }

    @Override
    public void updateArea(AreaForm form) {
        Area entity = areaConverter.toEntity(form);
        this.updateById(entity);
    }

    @Override
    public boolean deleteArea(Long areaId) {
        return this.removeById(areaId);
    }
}
